﻿using System.Diagnostics;
using System.Runtime.Serialization;
using Game.ExtensibleObjects;
using Game.Terrain;

namespace Game.Map.Extensions
{
    public static class TerrianExtensionHelper
    {
        public static TerrianExtension TerrianX(this IMapField field)
        {
            return field.Extensions.Find<TerrianExtension>();
        }

        public static double CalcTerrainCost(
            this GamePath path,
            IGameMap map)
        {
            var cost = 0d;
            for (int i = 1; i < path.Points.Count; i++)
            {
                var point = path.Points[i];
                var field = map.Fields[point];
                cost += TerrianX(field).TerrainCost;

                Debug.Assert(TerrianX(field).TerrainCost > 0);
            }

            return cost;
        }

    }

    [DataContract(Namespace = "game")]
    public class TerrianExtension : IRuntimeExtension, IAttachable
    {
        IMapField _Field;

        [DataMember]
        public TerrainType TerrainType { get; set; }

        public TerrianExtension(IRuntimeExtensibleObject obj)
        {
            _Field = obj as IMapField;
            TerrainType = TerrainType.DefaultTerrainType;
        }

        public void Attach(IRuntimeExtensibleObject field)
        {
            _Field = field as IMapField;
        }

        public int AttackBonus
        {
            get { return TerrainType.AttackBonus; }
        }

        public int DefenseBonus
        {
            get { return TerrainType.DefenseBonus; }
        }

        public double TerrainCost
        {
            get
            {
                var cost = TerrainType.TerrainBits.Cost;
                cost += (_Field.ObjectX().GameObject != null ? _Field.ObjectX().GameObject.TerrainCost : 0);

                Debug.Assert(cost > 0);
                return cost;
            }
        }
    }

    public class TerrianExtensionFactory : IRuntimeExtensionFactory
    {
        public IRuntimeExtension CreateExtension(IRuntimeExtensibleObject source)
        {
            return new TerrianExtension(source);
        }
    }
}
